import React, { Component } from 'react'
//路由传参
import {withRouter} from "react-router-dom"
import {Modal, Button, WhiteSpace, WingBlank,Toast,Carousel } from "antd-mobile"
import "./index.scss"
import { BASE_URL } from '../../utils/requestPath'
import requestAxios from '../../utils/myaxios'

const operation = Modal.operation;
class Index extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
          selectedTab: 'redTab',
          hidden: false,
          fullScreen: false,
          naviagtorOrderStart:true,
          JumpItem:true,
          clearNaviagtorOrderTop:false,
          naviagtorOrderStartTop:false,
          tabBarColor:"white",
          goodsList:[
          ],
          userCountIntegral:0,
          goodsZIndex:500,
          goodsDetail:false,
          data: ['1', '2', '3'],
          imgHeight: 176,
          goodsDetailInst:{},
          userInfoNew:{},
          marginTop:null
        };
      }
    
      componentDidMount(){
        document.title="EZblu导航"
        window.addEventListener('scroll', this.handleScroll);
        //debugger
        this.componentIntegral()
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
        this.getGoodsList()
        if(user.jumpStart === 1){
          this.setState({
            naviagtorOrderStart:false,
            JumpItem:false
          })
        }

        //轮播.....
        setTimeout(() => {
            this.setState({
              data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
            });
        }, 100);
        
        //get user
        this.getUserInfo()
      }

      getGoodsList=()=>{
          requestAxios.post(BASE_URL+"/api/goods/find/all/0/0",).then(res=>{
              this.setState({
                  goodsList:res.data.data
              })
          })
      }
    
      naviagtorOrderStart = ()=>{
          this.setState({
            naviagtorOrderStart:false,
            clearNaviagtorOrderTop:true,
            naviagtorOrderStartTop:true,
          })
      }
    
      clearNaviagtorOrder = ()=>{

        this.clearNaviagtorOrderTop()
      }
    
      requestAxiosJump = () =>{
        const userInfoIns = localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
          const id = user.id;
          const jumpStart = 1;
          const userInfo = {id,jumpStart};
          // axios set jump == 1
          //debugger
          requestAxios.put(BASE_URL+"/api/user/update",userInfo).then(res=>{
                console.log(res)
          })
      }
    
      clearNaviagtorOrderTop = ()=>{
        this.setState({
          clearNaviagtorOrderTop:false,
          JumpItem:false
        })
    
        // axios set jump == 1
        this.requestAxiosJump()
      }
    
      naviagtorOrderStartTop = ()=>{
    
        // if 知道了....... request
        this.clearNaviagtorOrderTop()
      }


      async integralExchangeRequest(value){
        //alert("缓存打印......进来了")
        //缓存......
        const jumpStartStr = localStorage.getItem("jumpStart")
        if(jumpStartStr === null){
           this.requestAxiosJump()
           this.setState({
                goodsZIndex:0
           })
        }

        //兑换用户id
        const integralUserId = localStorage.getItem("userInfoIns");
        const integralUserInfo = JSON.parse(integralUserId) || {}
        await localStorage.setItem("jumpStart",JSON.stringify(1))

        //用多少积分兑换 
        if(integralUserInfo.id){
            let zgUserId = integralUserInfo.id;
            let goodsId = parseInt(value.id)
            let exchangeState = 1
            let goodsIntegralExchange = value.goodsIntegralExchange
            let goodsExchange = {zgUserId,exchangeState,goodsIntegralExchange,goodsId};
            await requestAxios.post(BASE_URL+"/api/goods/exchange/add",goodsExchange).then(res=>{
                if(res.data.flag){
                    console.log("兑换成功,请在兑换记录列表查看")
                    Toast.success('兑换成功,存入兑换列表!!!', 2);
                }else{
                    Toast.offline(res.data.message, 1);
                    return;
                }

            })
            await this.componentIntegral()
            await this.props.onClicked()

        }
        
    }

    integralExchangeRequestPrice=(value)=>{
        //兑换用户id
        const integralUserId = localStorage.getItem("userInfoIns");
        const integralUserInfo = JSON.parse(integralUserId) || {}

        //用多少积分兑换 
        if(integralUserInfo.id){
            let zgUserId = integralUserInfo.id;
            // let goodsId = parseInt(value.id)
            let exchangeState = 2
            let goodsIntegralExchange = value
            let goodsExchange = {zgUserId,exchangeState,goodsIntegralExchange};
            requestAxios.post(BASE_URL+"/api/goods/exchange/add",goodsExchange).then(res=>{
                if(res.data.flag){
                    console.log("兑换成功,请在兑换记录列表查看")
                    Toast.success('兑换成功,存入兑换列表!!!', 2);
                    this.componentIntegral()
                }else{
                    Toast.offline(res.data.message, 1);
                    return;
                }

            })
 
        }

        //调用...
        this.requestAxiosJump()
    }

    integralExchangeRequestXj=async(value)=>{
        //兑换用户id
        const integralUserId = localStorage.getItem("userInfoIns");
        const integralUserInfo = JSON.parse(integralUserId) || {}
        //await localStorage.setItem("jumpStart",JSON.stringify(1))

        //用多少积分兑换 
        if(integralUserInfo.id){
            let zgUserId = integralUserInfo.id;
            //let goodsId = parseInt(value.id)
            let exchangeState = 2;
            let exchangePrice = value;
            let goodsIntegralExchange = value.goodsIntegralExchange;
            let goodsExchange = {exchangeState,goodsIntegralExchange,exchangePrice};
            await requestAxios.post(BASE_URL+"/api/goods/exchange/add",goodsExchange).then(res=>{
                if(res.data.flag){
                    console.log("兑换成功,请在兑换记录列表查看")
                    Toast.success('兑换成功,存入兑换列表!!!', 2);
                }else{
                    Toast.offline(res.data.message, 1);
                    return;
                }

            })
            await this.componentIntegral()
            await this.props.onClicked()

        }
    }


    //get integral
    componentIntegral=()=>{
        const userInfos = localStorage.getItem("userInfoIns");
        const userInfoIns = JSON.parse(userInfos) || {};

        console.log("integral.......打印")
        console.log(userInfoIns)

        if(userInfoIns){
            //获取用户当前的积分
            requestAxios.get(BASE_URL+"/api/integral/find/list/"+userInfoIns.id).then(res=>{

                console.log(res.data)
                this.setState({
                    userCountIntegral:res.data
                })
            })
        }
    }


    //商品详情
    onGoodsListDetail=(value)=>{
        
        console.log("商品详情.....")
        //console.log(value)
        this.setState({
            goodsDetail:true,
            goodsDetailInst:value
        })

        //alert(value)
    }

    //关闭详情
    clearGoodsDetail=()=>{
        this.setState({
            goodsDetail:false
        })
    }

    //get user info
    getUserInfo= async()=>{

        const userInfoIns =await localStorage.getItem("userInfoIns")
        const user = JSON.parse(userInfoIns) || {}
    
        await requestAxios.get(BASE_URL+"/api/user/getid/"+user.id).then(res=>{
           this.setState({
            userInfoNew:res.data
           })
        })
    
      }

    //   handleScroll=async()=>{
    //     console.log(window.scrollY)
    //     let clientHeight = this.refs.bodyBox.clientHeight; //可视区域高度
    //     let scrollTop  = this.refs.bodyBox.scrollTop;  //滚动条滚动高度
    //     let scrollHeight = this.refs.bodyBox.scrollHeight; //滚动内容高度
    //     await this.setState({
    //       marginTop:parseInt(scrollTop) - 125
    //     })
    //     console.log("clientHeight",clientHeight)
    //     console.log("scrollTop",scrollTop)
    //     console.log("scrollHeight",scrollHeight)
    //   }

    render(){
        const {reSet,userCountIntegral,goodsDetailInst} = this.state
        return (
           <>
                 {/* 积分兑换 */}
            <div  className="main-integral-exchange" >
                <h4>代金引換</h4>
                <div className="main0integral-300-500-1000">
                    {/* 300日元优惠券 */}
                    {this.state.goodsList.map((value,index)=>{
                        return (
                                <div 
                                key={index}
                                //style={index === 0?{zIndex:this.state.goodsZIndex,background:"#fff"}:{}}
                                className="main-integral-300-goods" 
                                    >
                                {/* <div className="main-integral-top-goods"
                                onClick={this.onGoodsListDetail.bind(this,value)}
                                >
                                    <h4>{value.goodsName}</h4>
                                    <h5>{value.goodsIntegralExchange}分兑换</h5>
                                    
                                </div> */}
                                <Button 
                                className="main-integral-bottom"
                                style={{fontSize:14,}}
                                onClick={() => operation([
                                    { text:value.goodsName,style:{textAlign:'center',color:"rgb(235, 37, 4)",fontWeight:900}},
                                    { text: '立即兑换',style:{background:"skyblue",color:"#fff",textAlign:"center"}, onPress: async() => {
                                        
                                        //alert("确定.....")
                                        // //获取当前用户积分,并且赋值.....
                                        await this.componentIntegral()
                                       
                                        //先弹出,后赋值....
                                        // if(this.state.userInfoNew.jumpStartTwo !== 1){
                                        //     localStorage.setItem("jumpStartThree",3)
                                        //     //debugger
                                        //     await this.props.onClicked()
                                        // }

                                        await this.getUserInfo()
                                        
                                        // //判断当前用户的积分和当前商品的积分是否足够
                                        if(parseInt(userCountIntegral) < parseInt(value.goodsIntegralExchange)){
                                            Toast.offline('积分不够请充值 !!!', 1);
                                            return;
                                        }

                                        Toast.loading('Loading...', 1, () => {
                                            console.log('Load complete !!!');
                                        });

                                        // //添加兑换信息....
                                        this.integralExchangeRequest(value)

                                        //乐天,雅虎商品列表,,,,兑换成功,像父组件传递参数或缓存localStorage设置jumpStart........
                                        //,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
                                        //this.props.fuOnClickedStart()
                                        
                                        await this.requestAxiosJump()
                                        // if(jumpStartStr === 1){
                                            
                                        // }
                                        
                                    }},
                                    ])}
                                >代金</Button>
                                <div onClick={this.onGoodsListDetail.bind(this,value)} className="main-goods-integral-images"> 
                                    <img src={value.goodsImg}></img>
                                    
                                </div>
                                <h3>{value.goodsName}</h3>
                                <h3 className="main-goods-integral-bottom-h3">代金<span>{value.goodsIntegralExchange}</span></h3>
                            </div>
                        )
                    })}
                    {/* 500日元优惠券 */}

                    {/* 1000积分现金返现 */}
                            <div 
                                className="main-integral-300-1000" 
                                    >
                                <div 
                                className="main-goods-integral-images"> 
                                    <img src="http://qiniuyun.ezbluvip.com/4-1.png"></img>
                                    
                                </div>
                                <h3 className="top1">1000现金返现</h3>
                                <h4 className="top2">受け取り</h4>
                                <h3 className="main-goods-integral-bottom-h3">积分<span>{10000}</span></h3>
                                
                            </div>

                    {/* 1000积分现金返现结束 */}


                </div>
                {/* goodsDetail 商品详情..... */}
                {this.state.goodsDetail? 
                    <div className="goodsIntegralDetail" 
                    //style={{top:-125}}
                    >
                        <h2 className="goodsTitle">{goodsDetailInst.goodsName}</h2>
                        <p><span className="goodsIntegralspan1">兑换积分:</span><span className="goodsIntegralspan2">{goodsDetailInst.goodsIntegralExchange}</span> </p>
                            <Carousel
                                autoplay={true}
                                infinite
                                beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
                                afterChange={index => console.log('slide to', index)}
                                >
                                {this.state.data.map((val,indexs) => (
                                    <a
                                    key={val}
                                    href=""
                                    style={{ display: 'inline-block', width: '100%', height: this.state.imgHeight }}
                                    >
                                    <img
                                        src={`${goodsDetailInst.goodsImg}`}
                                        alt=""
                                        style={{ width: "100%",height:140, verticalAlign: 'top' }}
                                        onLoad={() => {
                                        window.dispatchEvent(new Event('resize'));
                                        this.setState({ imgHeight: 'auto' });
                                        }}
                                    />
                                    </a>
                                ))}
                            </Carousel>
                        <div className="goodsDetailDesc">
                            {goodsDetailInst.goodsDesc}
                        </div>
                        <h3 onClick={this.clearGoodsDetail}>
                        ×
                        </h3>
                    </div>
                :""}
            </div>
           </>
        )
    }

} 
export default Index;